package com.project.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.project.bean.*;
import com.project.dto.*;
import com.project.mapper.IBeautifyMapper;
import com.project.mapper.IOrderInfoMapper;
import com.project.mapper.IOrderMapper;
import com.project.mapper.IUserMapper;
import com.project.service.*;
import com.project.util.ConvertBeanUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
public class MQController {
    @Autowired
    private IProcureApplyService procureApplyService;

    @Autowired
    private IPutInStorageService putInStorageService;
    @Autowired
    private IBeautifyMapper beautifyMapper;
    @Autowired
    private IDiscountApplyService discountApplyService;
    @Autowired
    private IDiscountService discountService;
    @Autowired
    private IOrderMapper orderMapper;
    @Autowired
    private IOrderInfoMapper orderInfoMapper;
    @Autowired
    private IOrderService orderService;

    @Autowired
    private IUserMapper userMapper;

    /**
     * 监听采购申请表的审核结果信息
     * 并且修改状态
     * @param
     */
    @RabbitListener(queues = "ProcureApplySupplierVerifyResult")
    void ProcureApplyResult(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, String  message ) throws IOException {
        ProcureApplyDto procureApplyDto= JSONObject.parseObject(message,ProcureApplyDto.class);

        String st=procureApplyService.updateStatus(procureApplyDto.getApplyRef(), procureApplyDto.getStatus());
        if (st=="ok" &&procureApplyDto.getStatus()==2){
            procureApplyService.updateAuditReason(procureApplyDto.getApplyRef(), procureApplyDto.getCause());
        }
        channel.basicAck(tag, false); //tag标志，false-不批量确认
    }






    /**
     *促销审核结果
     */
    @RabbitListener(queues = "PromotionVerifyResult")
    public void DiscountApplyResult(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag,String message) throws IOException {
        PromotionDto promotionDto=JSONObject.parseObject(message, PromotionDto.class);
        if (promotionDto.getStatus()==1){//状态为1，表示审核通过，修改审核状态即审核结果
            discountApplyService.updateStatusByDiscountApplyId(promotionDto.getPromotionRef(), "审核通过");
            discountApplyService.updateReasonByDiscountApplyId(promotionDto.getPromotionRef(), "审核通过");
            discountService.updatePromotionById(promotionDto.getProductRef(),"促销");
        }else if (promotionDto.getStatus()==2){//状态为2，表示审核不通过，修改审核状态即审核结果
            discountApplyService.updateStatusByDiscountApplyId(promotionDto.getPromotionRef(), "审核不通过");
            discountApplyService.updateReasonByDiscountApplyId(promotionDto.getPromotionRef(), promotionDto.getCause());
        }
        channel.basicAck(tag, false); //tag标志，false-不批量确认
    }

    /**
     * 监听退货商品，并将其添加到库存
     * @param message
     */
    @RabbitListener(queues = "sendUserRefundOrder")
    void goodsRejected(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag,String message) throws IOException {
        System.out.println("打印结果");
        System.out.println(message);

        RefundOrderDto refundOrderDto= JSONObject.parseObject(message, RefundOrderDto.class);


        OrderBean orderBean=new OrderBean();
        orderBean=orderService.findOrderByOrderId( refundOrderDto.getRet_id());
        orderService.updateStatus( orderBean.getOrderNum());
        //退货商品详情
        List<OrderInfoBean>list=orderService.findByOrderId(refundOrderDto.getRet_id());
        List<OrderReturnProductBean>orderList=new ArrayList<>();
        for (int i=0; i<list.size();i++){
            OrderInfoBean infoBean=list.get(i);
            OrderReturnProductBean order=new OrderReturnProductBean(
                orderBean.getOrderNum(),infoBean.getCommodityId(),
                    infoBean.getCommodityName(),
                    infoBean.getCommodityNum(),
                    infoBean.getCommodityPrice(),
                    infoBean.getColor(),
                    infoBean.getType(),
                    infoBean.getSize()
            );
            orderList.add(i,order);
        }
        //退货商品订单表
        CusReturnBean cusReturnBean=new CusReturnBean(
                orderBean.getOrderNum(),
                orderBean.getTotalPrice(),
                refundOrderDto.getDate(),"未入库",
                        orderBean.getCustomerName(),orderList);


//        UserOrderRefundEntity userOrderRefundEntity=new UserOrderRefundEntity();
        putInStorageService.goodsRejected(cusReturnBean);
        channel.basicAck(tag, false); //tag标志，false-不批量确认

    }


    /**
     * 监听供应商的供货商品，并将其添加到数据库
     * @param message
     */
    @RabbitListener(queues = "sendSupplyOrder")
    void joinSupplyGoods(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag,String message) throws IOException {
        System.out.println(message);
        SupplyToCscDto supplyToCscDto= JSONObject.parseObject(message, SupplyToCscDto.class);
        SupplyInfoBean supplyInfoBean=new SupplyInfoBean(
                String.valueOf(supplyToCscDto.getSupplyRef()),
                supplyToCscDto.getBatch(),
                supplyToCscDto.getSupplierName(),
                supplyToCscDto.getMoney(),
                supplyToCscDto.getDateTime());
        List<GoodsToCscDto> goodsToCscDtoList=supplyToCscDto.getSupplyGoodsEntityList();
        List<InProductBean> procureBeanList=new ArrayList<>();
//        List<>
        for (int i=0;i<goodsToCscDtoList.size();i++){
            GoodsToCscDto goodsToCscDto=goodsToCscDtoList.get(i);
            InProductBean inProductBean=new InProductBean(
                    goodsToCscDto.getGoodsName(),
                    goodsToCscDto.getType(),
                    goodsToCscDto.getSum(),
                    goodsToCscDto.getColor(),
                    goodsToCscDto.getSize(),
                    (int) goodsToCscDto.getPrice(),
                    supplyToCscDto.getBatch());
            procureBeanList.add(i,inProductBean);
        }
        //将商品添加进入商品详情
        supplyInfoBean.setInProductBeans(procureBeanList);

        putInStorageService.SupplyGoods(supplyInfoBean);
        channel.basicAck(tag, false); //tag标志，false-不批量确认

    }

    /**
     * 监听前端美化商品
     * @param
     */
    @RabbitListener(queues = "beautifyProduct")
    public void receiveMessage(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag,String message) throws IOException{
        System.out.println(message);
        BeautifyProductDto beautifyProductDto=JSONObject.parseObject(message,BeautifyProductDto.class);

        // 将 BeautifyProductDto 转换为 BeautifyBean 对象
        BeautifyBean beautifyBean = new BeautifyBean();
        beautifyBean.setProductNum(beautifyProductDto.getProductNum());
        beautifyBean.setDescribt(beautifyProductDto.getDescribe());
        beautifyBean.setSellPrice(beautifyProductDto.getSellPrice());
        beautifyBean.setStatus("未审核");
        beautifyBean.setReason("");

        // 插入到本地数据库中

        beautifyMapper.insert(beautifyBean);
        channel.basicAck(tag, false); //tag标志，false-不批量确认
    }

    /**
     * 接受用户订单
     */
    @RabbitListener(queues = "addOrderEnd")
    public void addOrder(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, String json) throws IOException {
        try {
            // 解析json字符串为UserOrderEntity对象
            UserOrderEntity userOrderEntity = JSON.parseObject(json, UserOrderEntity.class);

            // 将UserOrderEntity对象转换为OrderBean对象
            OrderBean orderBean = new OrderBean();
            orderBean.setOrderNum(userOrderEntity.getOrderRef());
            orderBean.setTotalPrice(userOrderEntity.getTotalPrice());
            orderBean.setStatus(userOrderEntity.getStatus());

            //地址里面是详细地址，包含用户详细（例如：收货人abc电话号码15874124712山西省省晋中市市寿阳县区一栋3单元401）
            String addressInfo = userOrderEntity.getAddress();
            String name = null;
            String phone = null;
            Pattern pattern = Pattern.compile("收货人(\\S+)电话号码(\\d+)");
            Matcher matcher = pattern.matcher(addressInfo);
            if (matcher.find()) {
                name = matcher.group(1);
                phone = matcher.group(2);
            }


            orderBean.setAddress(userOrderEntity.getAddress());
            int payCode = userOrderEntity.getModeOfPayment();
            String payStr = null;
            if (payCode == 0){
                payStr = "预支付";
            }
            else if (payCode == 1){
                payStr = "支付宝";
            }
            orderBean.setModeOfPayment(payStr);//支付方式

            orderBean.setCustomerName(name);
            orderBean.setPhone(phone);;

            List<OrderInfoBean> orderInfoList = userOrderEntity.getUserOrderInfoProductEntityList().stream()
                    .map(OrderInfoBean::fromUserOrderInfoProductEntity)
                    .collect(Collectors.toList());
            orderBean.setOrderInfoList(orderInfoList);

            // 将OrderBean对象插入本地数据库
            orderMapper.insert(orderBean);
            for (OrderInfoBean orderInfoBean : orderInfoList){
                orderInfoMapper.insert(orderInfoBean);
            }

            // 确认消息已经被消费
            channel.basicAck(tag, false);
        } catch (Exception e) {
            // 发生异常时，拒绝消息并重新入队
            channel.basicAck(tag, true);
            e.printStackTrace();
        }
    }
    /**
     * 监审核通过后的用户，并添加到本地用户
     */
    @RabbitListener(queues = "UserVerifySuccess")
    public void addUserFormSH(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, String json) throws IOException {
        //将接收到的dto转为本地
        UserDto userDto = JSON.parseObject(json, UserDto.class);
        UserBean userBean= ConvertBeanUtil.copy(userDto,UserBean.class);
        userMapper.insert(userBean);
    }

}
